package com.wrb.pwd.config;

import com.wrb.pwd.service.UserService;
import sun.misc.IOUtils;

import java.io.*;
import java.net.URLDecoder;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

/**
 * @author wrb
 * @date 2019/9/12 14:45
 */
public class RePackageThread extends Thread {

	@Override
	public void run() {
		pack();
	}

	/**
	 * 打包jar包并把资源文件导入
	 */
	public void pack() {
		try (ByteArrayOutputStream bArrOS = new ByteArrayOutputStream()) {
			String jarPath = RePackageThread.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			jarPath = URLDecoder.decode(jarPath, "utf-8");
			File file = new File(jarPath.substring(0, jarPath.lastIndexOf("/")) + "/" + UserService.DATA_FILE_NAME);
			if (!file.exists()) {
				return;
			}
			try (
					JarFile jarFile = new JarFile(jarPath);
					JarOutputStream jos = new JarOutputStream(bArrOS)
			) {
				jarFile.stream().forEach(entry -> {
//					System.out.println(entry.getName());
					try (InputStream is = jarFile.getInputStream(entry)) {
						jos.putNextEntry(new JarEntry(entry.getName()));

						if (UserService.DATA_FILE_NAME.equals(entry.getName())) {
							FileInputStream fis = new FileInputStream(file);
							String s = parseString(fis);
							jos.write(s.getBytes());
							fis.close();
							file.delete();
						} else {
							jos.write(IOUtils.readNBytes(is, is.available()));
						}

						jos.closeEntry();
					} catch (Exception e) {
						e.printStackTrace();
					}
				});
			}

			bArrOS.writeTo(new FileOutputStream(jarPath));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String parseString(InputStream in) throws Exception {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		int ch;
		while ((ch = in.read()) != -1) {
			swapStream.write(ch);
		}
		return swapStream.toString();
	}
}
